package com.demo01.server;

import com.demo01.core.HelloPacket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.core.PacketSendMode;
import org.tio.core.Tio;
import org.tio.core.TioConfig;
import org.tio.core.exception.TioDecodeException;
import org.tio.core.intf.Packet;
import org.tio.server.intf.ServerAioHandler;
import org.tio.utils.lock.SetWithLock;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;


public class ServerDemoHandler implements ServerAioHandler {
    private static final Logger log = LoggerFactory.getLogger(ServerDemoHandler.class);

    public static String bytesToHex(byte[] byteArray) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : byteArray) {
            hexString.append(String.format("%02X", b));
        }
        return hexString.toString();
    }

    @Override
    public Packet decode(ByteBuffer buffer, int limit, int position, int readableLength, ChannelContext channelContext) {
        byte[] packetData = new byte[readableLength];
        buffer.get(packetData, position, readableLength);
        HelloPacket helloPacket = new HelloPacket();
        helloPacket.setBody(packetData);
        return helloPacket;
    }

    @Override
    public ByteBuffer encode(Packet packet, TioConfig tioConfig, ChannelContext channelContext) {
        HelloPacket helloPacket = (HelloPacket) packet;
        ByteBuffer buffer = ByteBuffer.wrap(helloPacket.getBody());

        return buffer;
    }

    @Override
    public void handler(Packet packet, ChannelContext channelContext) throws Exception {

        HelloPacket helloPacket = (HelloPacket) packet;
        String logFormat = "packet , msg={}, userId={}, ip={}";
        String ip = channelContext.getClientNode().getIp();
        int port = channelContext.getClientNode().getPort();
        String string;
        byte[] packetData = helloPacket.getBody();
        if ((packetData[0] & 0xFF) == 0xFB) {
            if (channelContext.userid == null) {
                Tio.bindUser(channelContext, "4000000");
            }
            string = bytesToHex(packetData);
        } else {
            string = new String(packetData, StandardCharsets.UTF_8);
            if (string.contains("usr.cnAT+")) {
                if (channelContext.userid == null) {
                    String userId = String.format("%s%d",ip, port);
                    Tio.bindUser(channelContext, "5000000");
                }
                log.info("from local client");
                Tio.sendToUser(channelContext.tioConfig, "4000000",helloPacket);
            }else{
                Tio.sendToUser(channelContext.tioConfig, "5000000",helloPacket);
            }
        }
        log.info(logFormat, string, channelContext.userid, ip);
    }

}
